<template>
    <mescroll-uni @init="mescrollInit" :up="upOption" :down="downOption" @down="downCallback" @up="upCallback">
        <!-- 搜索栏 -->
        <view class="search-header">
            <view class="search-container">
                <input class="search-input" 
                       v-model="searchForm.xiqukepuName" 
                       type="text" 
                       placeholder="搜索中医药科普名称">
                <view class="action-buttons">
                    <button class="btn search-btn" @tap="search">搜索</button>
                    <button v-if="isAuth('xiqukepu','新增')" 
                            class="btn add-btn" 
                            @click="onAddTap">新建</button>
                    <button class="btn filter-btn" @click="showDrawer">分类</button>
                </view>
            </view>
        </view>

        <!-- 分类侧边栏 -->
        <uni-drawer ref="showRight" mode="left" :maskClick="true" :width="220">
            <scroll-view class="category-sidebar">
                <view class="category-list">
                    <view v-for="(item,index) in xiqukepuTypesList" 
                          :key="index" 
                          class="category-item"
                          :class="{active: xiqukepuTypes===item.codeIndex}"
                          @tap="xiqukepuTypesCategoryClick(item.codeIndex)">
                        {{item.indexName}}
                        <view class="indicator-dot"></view>
                    </view>
                </view>
            </scroll-view>
        </uni-drawer>

        <!-- 内容列表 -->
        <view class="knowledge-list">
            <view v-for="(item,index) in list" 
                  :key="index" 
                  class="knowledge-card"
                  @tap="onDetailTap(item)">
                <view class="card-header">
                    <text class="title">{{item.xiqukepuName}}</text>
                    <text class="date">{{item.insertTime.split(" ")[0]}}</text>
                </view>
                <view class="content-preview" v-html="item.xiqukepuContent"></view>
                <view class="card-footer">
                    <text class="read-more">查看详情</text>
                    <view class="deco-line"></view>
                </view>
            </view>
        </view>
    </mescroll-uni>
</template>


<script>
	export default {
		data() {
			return {
                user:{},//当前登录表的所有参数
                sessionTable : uni.getStorageSync("nowTable"),//登录账户所在表名
                role : uni.getStorageSync("role"),//权限
                userId:uni.getStorageSync("userid"),//当前登录人的id
                btnColor: ['#67c23a', '#909399', '#e6a23c', '#f56c6c', '#356c6c', '#3498db', '#f093a9',
                    '#a7c23a', '#104eff', '#90f794', '#a21233', '#8e44ad'
                ],
				queryList: [{
						queryName: "中医药科普科普名称",
					}
				],
                sactiveItem: {
                    "padding": "0",
                    "boxShadow": "0 0 0px rgba(0,0,0,.3)",
                    "margin": "0 10rpx",
                    "borderColor": "rgba(0,0,0,1)",
                    "backgroundColor": "var(--publicMainColor)",
                    "color": "#fff",
                    "borderRadius": "0 40rpx 40rpx 0",
                    "borderWidth": "0",
                    "width": "auto",
                    "lineHeight": "160rpx",
                    "fontSize": "28rpx",
                    "borderStyle": "solid"
                },
                sitem: {
                    "padding": "0",
                    "boxShadow": "0 0 0px rgba(0,0,0,.3)",
                    "margin": "0 10rpx",
                    "borderColor": "rgba(0,0,0,1)",
                    "backgroundColor": "var(--publicSubColor)",
                    "color": "#fff",
                    "borderRadius": "0 40rpx 40rpx 0",
                    "borderWidth": "0",
                    "width": "auto",
                    "lineHeight": "160rpx",
                    "fontSize": "28rpx",
                    "borderStyle": "solid"
                },

				list: [],
				mescroll: null, //mescroll实例对象
				downOption: {
					auto: false //是否在初始化后,自动执行下拉回调callback; 默认true
				},
				upOption: {
					noMoreSize: 5, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					textNoMore: '~ 没有更多了 ~',
				},
				hasNext: true,
				searchForm: {},
				/*1111*/
				xiqukepuTypesList: [],
                xiqukepuTypes: 0,

				CustomBar: '0'
			};
		},
        computed: {
            baseUrl() {
                return this.$base.url;
            },
        },
		async onShow() {
			this.btnColor = this.btnColor.sort(() => {
				return (0.5 - Math.random());
			});

            let _this = this
            let table = uni.getStorageSync("nowTable");
            // 获取用户信息
            let resA = await _this.$api.session(table);
            _this.user = resA.data;
            _this.btnColor = _this.btnColor.sort(() => {
                return (0.5 - Math.random());
            });

                //当前表的 中医药科普科普类型 字段 字典表查询方法
                this.xiqukepuTypesSelect()



			this.hasNext = true
			// 重新加载数据
			if (this.mescroll) this.mescroll.resetUpScroll()
		},
		onLoad() {
			this.hasNext = true
			// 重新加载数据
			if (this.mescroll) this.mescroll.resetUpScroll()
		},
		methods: {
		    //类型条件查询
            async showDrawer() {
                this.$refs.showRight.open();
            },
            async closeDrawer() {
                this.$refs.showRight.close();
            },
            //下载
            download(url) {
                let _this = this;
                uni.downloadFile({
                    url: url,
                    success: (res) => {
                        if (res.statusCode === 200) {
                            _this.$utils.msg('下载成功');
                            window.open(url);
                        }
                    }
                });
            },
            //当前表的 中医药科普科普类型 字段 字典表查询方法
            async xiqukepuTypesSelect(){
                let xiqukepuTypes = await this.$api.page('dictionary', {
                    page: 1,
                    limit: 100,
                    dicCode:'xiqukepu_types',
                });
                xiqukepuTypes.data.list.splice(0, 0, {codeIndex: 0, indexName: '全部'})
                this.xiqukepuTypesList = xiqukepuTypes.data.list
            },
            //当前表的 中医药科普科普类型字段类别搜索
			xiqukepuTypesCategoryClick(categoryName) {
                this.xiqukepuTypes = categoryName;
                this.mescroll.resetUpScroll();
            },
            //查询条件切换
            queryChange(e) {
                this.searchForm.xiqukepuName = "";
            },
			// mescroll组件初始化的回调,可获取到mescroll对象
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调 */
			downCallback(mescroll) {
				this.hasNext = true
				// 重置分页参数页数为1
				mescroll.resetUpScroll()
			},
			/*上拉加载的回调: mescroll携带page的参数, 其中num:当前页 从1开始, size:每页数据条数,默认10 */
			async upCallback(mescroll) {
				let params = {
					page: mescroll.num,
					limit: mescroll.size,
				}

                if (this.xiqukepuTypes != 0) {
                    params.xiqukepuTypes = this.xiqukepuTypes
                }
                let _this = this
                let res = await this.$api.list(`xiqukepu`, params);
                res.data.list.forEach(function(item,index){
                    if(item.xiqukepuContent!=null){
                        item.xiqukepuContent = item.xiqukepuContent.replace("<img","<img  class=\"daxiao\"").replace("src=\"upload/","src=\""+_this.$base.url+"upload/");
                    }
                })

                if (mescroll.num == 1) this.list = [];
				this.list = this.list.concat(res.data.list);
				if (res.data.list.length == 0) this.hasNext = false;
				mescroll.endSuccess(mescroll.size, this.hasNext);
			},
			//添加地址
            onSelectTap(item) {
                uni.setStorageSync('address', item);
                uni.navigateBack({
                    delta: 1
                })
            },
			// 详情

			onDetailTap(item) {
				this.$utils.jump(`./detail?id=${item.id}`)
			},
			// 修改
			onUpdateTap(id) {
				this.$utils.jump(`./add-or-update?id=${id}`)
			},
			// 添加
			onAddTap() {
				this.$utils.jump(`./add-or-update`)
			},
			onDeleteTap(id) {
				var _this = this;
				uni.showModal({
					title: '提示',
					content: '是否确认删除',
					success: async function(res) {
						if (res.confirm) {
							await _this.$api.del('xiqukepu', JSON.stringify([id]));
							_this.hasNext = true
							// 重置分页参数页数为1
							_this.mescroll.resetUpScroll()
						}
					}
				});
			},
            onShenhe(data,shenheTypes) {
                var _this = this;
                uni.showModal({
                    title: '提示',
                    content: '确定要这个审核状态么?',
                    success: async function(res) {
                        if (res.confirm) {
                            var currentTime = new Date();
                            var year = currentTime.getFullYear();
                            var month = currentTime.getMonth() + 1 < 10 ? '0' + (currentTime.getMonth() + 1) : currentTime.getMonth() + 1;
                            var day = currentTime.getDate() < 10 ? '0' + currentTime.getDate() : currentTime.getDate();
                            var hour = currentTime.getHours();
                            var minute = currentTime.getMinutes();
                            var second = currentTime.getSeconds();
                            var shijian=year + "-" + month + "-" + day + " " +hour +":" +minute+":"+second;

                            data.xiqukepuYesnoTypes=shenheTypes;
                            data.xiqukepuShenheTime=shijian;
                            await _this.$api.update(`xiqukepu`, data);
                            _this.hasNext = true
                            // 重置分页参数页数为1
                            _this.mescroll.resetUpScroll()
                        }
                    }
                });
            },
			// 搜索
			async search() {
				this.mescroll.num = 1
				let searchForm = {
					page: this.mescroll.num,
					limit: this.mescroll.size
				}
				if (this.searchForm.xiqukepuName) {
                    searchForm['xiqukepuName'] = this.searchForm.xiqukepuName
                }

                let res = await this.$api.list(`xiqukepu`, searchForm);
                let _this = this
                res.data.list.forEach(function(item,index){
                    if(item.xiqukepuContent!=null){
                        item.xiqukepuContent = item.xiqukepuContent.replace("<img","<img  class=\"daxiao\"").replace("src=\"upload/","src=\""+_this.$base.url+"upload/");
                    }
                })
				// 如果是第一页数据置空
				if (this.mescroll.num == 1) this.list = [];
				this.list = this.list.concat(res.data.list);
				if (res.data.list.length == 0) this.hasNext = false;
				this.mescroll.endSuccess(this.mescroll.size, this.hasNext);
			}
		}
	};
</script>
<style lang="scss">
/* 医疗健康主题色 */
:root {
    --primary-color: #00a67c;      // 主色（医疗绿）
    --secondary-color: #4a90e2;    // 辅助色（科技蓝）
    --accent-color: #ff9f43;       // 强调色（活力橙）
    --text-dark: #2d3436;         // 深色文字
    --text-light: #636e72;        // 浅色文字
    --bg-light: #f8f9fa;          // 背景色
    --border-color: #dfe6e9;      // 边框色
}

/* 搜索栏 */
.search-header {
    padding: 20rpx 24rpx;
    background: white;
    box-shadow: 0 2px 6px rgba(0,0,0,0.06);
    position: sticky;
    top: 0;
    z-index: 10;

    .search-container {
        display: flex;
        align-items: center;
        gap: 20rpx;
    }

    .search-input {
        flex: 1;
        height: 88rpx;
        padding: 0 32rpx;
        background: var(--bg-light);
        border-radius: 48rpx;
        font-size: 28rpx;
        color: var(--text-dark);
        border: 1px solid var(--border-color);
        
        &::placeholder {
            color: #b2bec3;
            font-weight: 300;
        }
    }

    .action-buttons {
        display: flex;
        gap: 16rpx;
    }

    .btn {
        padding: 0 32rpx;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 48rpx;
        font-size: 28rpx;
        font-weight: 500;
        transition: all 0.2s;
        
        &.search-btn {
            background: #6c5ce7;
            color: white;
            // box-shadow: 0 4rpx 12rpx rgba(0,166,124,0.3);
        }
        
        &.add-btn {
            background: linear-gradient(135deg, var(--accent-color), #ff6b6b);
            color: white;
        }
        
        &.filter-btn {
            background: #4a90e2;
            color: white;
        }
    }
}

/* 分类侧边栏 */
.category-sidebar {
    padding: 24rpx;
    background: white;

    .category-list {
        display: flex;
        flex-direction: column;
        gap: 8rpx;
    }

    .category-item {
        padding: 28rpx 32rpx;
        border-radius: 12rpx;
        background: var(--bg-light);
        color: var(--text-light);
        font-size: 28rpx;
        position: relative;
        transition: all 0.2s;

        &.active {
            background: rgba(var(--primary-color), 0.1);
            color: var(--primary-color);
            font-weight: 500;
            
            .indicator-dot {
                opacity: 1;
                transform: scale(1);
            }
        }

        .indicator-dot {
            position: absolute;
            right: 24rpx;
            top: 50%;
            transform: translateY(-50%);
            width: 12rpx;
            height: 12rpx;
            background: var(--primary-color);
            border-radius: 50%;
            opacity: 0;
            transition: all 0.2s;
        }
    }
}

/* 知识卡片列表 */
.knowledge-list {
    padding: 24rpx;
}

.knowledge-card {
    background: white;
    border-radius: 20rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
    transition: transform 0.2s;
    
    &:active {
        transform: scale(0.98);
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24rpx;

        .title {
            font-size: 32rpx;
            color: var(--text-dark);
            font-weight: 600;
            flex: 1;
            margin-right: 24rpx;
        }

        .date {
            font-size: 24rpx;
            color: var(--text-light);
            white-space: nowrap;
        }
    }

    .content-preview {
        font-size: 28rpx;
        color: var(--text-light);
        line-height: 1.6;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
        overflow: hidden;
        margin-bottom: 24rpx;
    }

    .card-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;

        .read-more {
            color: var(--primary-color);
            font-size: 26rpx;
            font-weight: 500;
        }

        .deco-line {
            width: 120rpx;
            height: 2rpx;
            background: var(--primary-color);
            opacity: 0.3;
        }
    }
}
</style>
